<script setup>
import coachApi from "@/api/coach.js";
import {ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {Plus} from '@element-plus/icons-vue'
//数据表格
const list = ref([])
const total = ref(0)
//分页信息和搜索条件
const coachQuery = ref({
    name: '',
    phone: '',
    page: 1,
    limit: 10
})

/*coachApi.list(coachQuery.value).then(result=>{
    list.value = result.data.records
    total.value = result.data.total
})*/

const loadData = () => {
    coachApi.list(coachQuery.value).then(result => {
        if (result.code == 0) {
            list.value = result.data.records
            total.value = result.data.total
        }
    })
}
loadData()

const onSearch = () => {
    coachQuery.value.page = 1
    loadData()
}

const reset = () => {
    coachQuery.value.name = ''
    coachQuery.value.phone = ''
}

//根据ID删除
const deleteById = (id) => {
    ElMessageBox.confirm(
        '您确认要删除吗？',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            coachApi.deleteById(id).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    loadData()
                } else {
                    ElMessage.error(result.msg)
                }
            })
        })
}

//批量删除
const ids = ref([])
const handleSelectionChange = (rows) => {
    console.log('多选', rows)
    ids.value = rows.map(row => row.id)
    console.log(ids.value)
}
const deleteAll = () => {
    ElMessageBox.confirm(
        '您确认要删除吗？',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            coachApi.deleteAll(ids.value).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    loadData()
                } else {
                    ElMessage.error(result.msg)
                }
            })
        })
}

//添加、编辑
const dialogFormVisible = ref(false)
const coach = ref({})
const showAddDialog = () => {
    coach.value = {}
    dialogFormVisible.value = true
}

const showUpdateDialog = (id) => {
    dialogFormVisible.value = true
    coach.value = {}
    coachApi.selectById(id).then(result => {
        if (result.code == 0) {
            coach.value = result.data
        }
    })
}

const addOrUpdate = () => {
    if (coach.value.id) {
        coachApi.update(coach.value).then(result => {
            if (result.code == 0) {
                ElMessage.success(result.msg)
                dialogFormVisible.value = false
                loadData()
            } else {
                ElMessage.error(result.msg)
            }
        })
    } else {
        coachApi.add(coach.value).then(result => {
            if (result.code == 0) {
                ElMessage.success(result.msg)
                dialogFormVisible.value = false
                loadData()
            } else {
                ElMessage.error(result.msg)
            }
        })
    }

}

// el-switch状态切换
const handleSwitchChange = (row) => {
    console.log(row)
    const coach = {}
    coach.id = row.id
    coach.status = row.status
    coachApi.update(coach).then(result => {
        if (result.code == 0) {
            ElMessage.success(result.msg);
        } else {
            ElMessage.error(result.msg)
        }
    })
}

//图片上传
const handleAvatarSuccess = (result) => {
    console.log('头像上传成功:', result);
    if (result.code === 0) {
        coach.value.avatar = result.data;
        ElMessage.success('头像上传成功');
    } else {
        ElMessage.error('头像上传失败: ' + (result.msg || '未知错误'));
    }
}

const handleAvatarError = (error) => {
    console.error('头像上传错误:', error);
    ElMessage.error('头像上传失败，请检查网络连接');
}

const beforeAvatarUpload = (file) => {
    console.log('准备上传头像:', file.name, '大小:', file.size);
    
    // 检查文件类型
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
        ElMessage.error('只能上传图片文件!');
        return false;
    }
    
    // 取消文件大小检查
    // const isLt5M = file.size / 1024 / 1024 < 5;
    // if (!isLt5M) {
    //     ElMessage.error('图片大小不能超过5MB!');
    //     return false;
    // }
    
    return true;
}
import {useTokenStore} from '@/store/token.js'
import WangEditor from "@/components/WangEditor.vue";

const tokenStore = useTokenStore();
const headers = ref({
    //携带token传递到后端
    Authorization: tokenStore.token
});

//富文本编辑器
const onEditorChange = (introduction) =>{
    coach.value.introduction = introduction
}


//简介
const dialogIntroductionVisible = ref(false)
const introduction = ref('')
const introductionTitle = ref('教练简介')
const showIntroduction = (intro) =>{
    dialogIntroductionVisible.value = true
    introduction.value = intro || '暂无简介'
    introductionTitle.value = '教练简介'
}

</script>

<template>
    <el-card class="">
        <template #header>
            <div class="header">
                <el-button type="primary" @click="showAddDialog">添加</el-button>
                <el-button type="primary" @click="deleteAll">批量删除</el-button>
            </div>
        </template>
        <el-form :inline="true">
            <el-form-item label="名字">
                <el-input v-model="coachQuery.name" placeholder="请输入名字" clearable style="width: 200px"/>
            </el-form-item>
            <el-form-item label="手机号">
                <el-input v-model="coachQuery.phone" placeholder="请输入手机号" clearable style="width: 200px"/>
            </el-form-item>
            <el-form-item label="更新时间" :label-width="100">
                <el-date-picker
                    v-model="coachQuery.beginUpdateTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="开始时间"
                />
                <el-date-picker
                    v-model="coachQuery.endUpdateTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="结束时间"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">搜索</el-button>
                <el-button type="danger" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column fixed prop="id" label="ID"/>
            <el-table-column prop="name" label="名字"/>
            <el-table-column prop="password" label="密码"/>
            <el-table-column prop="phone" label="电话"/>
            <el-table-column prop="email" label="邮箱"/>
            <el-table-column prop="status" label="状态">
                <template #default="scope">
                    <el-switch
                        v-model="scope.row.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        :active-value="1"
                        :inactive-value="0"
                        active-text="正常"
                        inactive-text="停用"
                        inline-prompt
                        @change="handleSwitchChange(scope.row)"
                    />
                </template>
            </el-table-column>
            <el-table-column prop="avatar" label="头像">
                <template #default="scope">
                    <img :src="scope.row.avatar" style="max-height: 40px; max-width: 120px;"/>
                </template>
            </el-table-column>
            <!-- <el-table-column prop="avatar" label="头像"/> -->
            <el-table-column prop="updateTime" label="更新时间" width="180px"/>
            <el-table-column align="center" width="200px" fixed="right" label="操作">
                <template #default="{ row }">
                    <el-button size="small" type="primary" @click="showUpdateDialog(row.id)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteById(row.id)">删除</el-button>
                    <el-button size="small" type="danger" @click="showIntroduction(row.introduction)">简介</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            v-model:current-page="coachQuery.page"
            v-model:page-size="coachQuery.limit"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @change="loadData"
            style="margin-top: 20px; justify-content: flex-end"
        />
    </el-card>

    <!--添加编辑弹出框-->
    <el-dialog v-model="dialogFormVisible" :title="coach.id ? '编辑教练' : '添加教练'" width="60%" :lock-scroll="false">
        <el-form :model="coach">
            <el-form-item label="名字" :label-width="60">
                <el-input v-model="coach.name" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="密码" :label-width="60">
                <el-input v-model="coach.password" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="邮箱" :label-width="60">
                <el-input v-model="coach.email" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="手机号" :label-width="60">
                <el-input v-model="coach.phone" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="照片" :label-width="60">
                <el-upload
                    class="avatar-uploader"
                    action="/api/upload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :on-error="handleAvatarError"
                    :before-upload="beforeAvatarUpload"
                    :headers="headers">
                    <img v-if="coach.avatar" :src="coach.avatar" class="avatar"/>
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus/>
                    </el-icon>
                </el-upload>
            </el-form-item>
            <WangEditor :initValue="coach.introduction" @getEditorContent="onEditorChange"
                        v-if="dialogFormVisible" @close="dialogFormVisible = false"></WangEditor>
            <el-form-item label="简介" :label-width="60">
                <el-input v-model="coach.introduction" autocomplete="off"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addOrUpdate">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!--简介弹出框-->
    <el-dialog v-model="dialogIntroductionVisible" :title="introductionTitle" width="60%" :lock-scroll="false">
        <div class="introduction-content">
            <div v-if="introduction && introduction !== '暂无简介'" v-html="introduction" class="introduction-text"></div>
            <div v-else class="no-introduction">
                <el-empty description="该教练暂无简介" :image-size="100"></el-empty>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="dialogIntroductionVisible = false">
                    关闭
                </el-button>
            </div>
        </template>
    </el-dialog>


</template>

<style scoped lang="scss">
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.introduction-content {
    min-height: 200px;
    max-height: 400px;
    overflow-y: auto;
    padding: 20px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background-color: #fafafa;
}

.introduction-text {
    line-height: 1.6;
    color: #606266;
    font-size: 14px;
}

.no-introduction {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200px;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>